﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ListForms;

namespace ListsForm
{
    public partial class FrmEditUser : FrmBaseEditForm
    {
        public FrmEditUser(Lists.Account account)
        {
            InitializeComponent();
            if (account == null)
            {
                _EditState = EditState.CreatingNew;
                bindingSource.AddNew();
                this.Text = "New Account";
                btnChangePassword.Enabled = false;
            }
            else
            {
                _EditState = EditState.Modifying;
                bindingSource.Add(DB.Accounts.FirstOrDefault(p => p.AccountID == account.AccountID));
                this.Text = "Edit Account";
                PasswordTextEdit.Properties.ReadOnly = true;
            }
            RoleIDTextEdit.Properties.DataSource = DB.AccessAuthorities.ToList();
            StaffIDTextEdit.Properties.DataSource = DB.Staffs.ToList();
        }

        protected override void CheckFullInfo()
        {
            Lists.Account account = (Lists.Account)bindingSource.Current;
            if (string.IsNullOrEmpty(account.AccountName))
                throw new Exception("Account name not allow null");
            if (string.IsNullOrEmpty(account.Password))
                throw new Exception("Password not allow null");
            //Kiểm tra trùng nhân viên (1 tài khoản chỉ dành cho 1 nhân viên)
            Lists.Account checkAccount = DB.Accounts.Where(p => p.StaffID == ((Lists.Account)bindingSource.Current).StaffID).FirstOrDefault();
            if (checkAccount != null)
            {
                if (checkAccount.AccountID != account.AccountID)
                    throw new Exception("This staff allready belong of another account");
            }
        }

        protected override void SaveAndClose()
        {
            Lists.Account account = (Lists.Account)bindingSource.Current;
            if (_EditState == EditState.CreatingNew)
            {
                account.AccountID = Guid.NewGuid();
                account.Password = GeneralLibs.CommonLib.MaHoaMD5(account.Password);
                DB.Accounts.InsertOnSubmit(account);
            }
            DB.SubmitChanges();
            this.Close();
        }

        private void btnChangePassword_Click(object sender, EventArgs e)
        {
            FrmChangePassword frm = new FrmChangePassword((Lists.Account)bindingSource.Current);
            frm.ShowDialog();
        }
    }
}
